package com.demo.villageresidence.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.demo.villageresidence.pojo.Files;
import com.demo.villageresidence.service.FilesService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/file")
public class FileController {
    @Value("${files.upload.path}")
    private String fileUploadPath;

    @Resource
    private FilesService filesService;
    //上传
    @PostMapping("/upload")
    public Map<String,Object> upload(@RequestParam MultipartFile file) throws IOException {
        Map<String,Object> resultMap = new HashMap<>();

        String originalFilename = file.getOriginalFilename(); //文件名.jpg
        String type = FileUtil.extName(originalFilename);//.jpg
        long size = file.getSize();//大小

        String uuid = IdUtil.fastSimpleUUID();
        String fileUUID = uuid + StrUtil.DOT + type; //41b1076684904f9cb4a503fb028db94b.jpg
        File uploadFile = new File(fileUploadPath + fileUUID);
        //先存储到磁盘
        if (!uploadFile.getParentFile().exists()) {
            uploadFile.getParentFile().mkdirs();
        }
        String url;
        file.transferTo(uploadFile);
        //获取文件的md5
        //使用m5 避免重复上传相同的文件
        String  md5 = SecureUtil.md5(uploadFile);
        Files dbFiles = getFileByMD5(md5);
        if (dbFiles != null) {
            url = dbFiles.getFileUrl();
            uploadFile.delete();
        } else {
            url = "http://localhost:9090/images/"+fileUUID;
        }
        //保存到数据库
        Files saveFile = new Files();
        saveFile.setFileName(originalFilename);
        saveFile.setFileType(type);
        saveFile.setFileSize(size / 1024);
        saveFile.setFileUrl(url);
        saveFile.setMd5(md5);
        filesService.save(saveFile);

        Map<String,Object> data = new HashMap<>();
        data.put("url",url);
        data.put("alt","");
        data.put("href","");

        resultMap.put("errno",0);
        resultMap.put("data", data);
        return resultMap;
    }

    //下载
    /*@GetMapping("/{fileUUID}")
    public void dowmload(@PathVariable String fileUUID,
                         HttpServletResponse response) throws IOException {

        File uploadFile = new File(fileUploadPath + fileUUID);
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Contene-Disposition","attachment;filename="+ URLEncoder.encode(fileUUID,"UTF-8"));
        response.setContentType("application/octet-stream");

        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }*/
    public Files getFileByMD5(String md5){
        List<Files> filesList =  filesService.query().eq("md5",md5).list();
        return filesList.size()==0? null: filesList.get(0);
    }
}

